<template>
  <div class="captcha-container">
    <canvas ref="captchaCanvas" :width="width" :height="height"></canvas>
    <input type="text" v-model="captchaInput" placeholder="请输入验证码" @input="$emit('update:modelValue', captchaInput)" />
    <button @click="generateCaptcha">刷新验证码</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const props = defineProps({
  modelValue: String
});

const emit = defineEmits(['update:modelValue']);

const width = 120;
const height = 40;
const captchaCanvas = ref(null);
const captchaInput = ref('');
const captcha = ref('');

const generateCaptcha = () => {
  const canvas = captchaCanvas.value;
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = '#eee';
  ctx.fillRect(0, 0, width, height);

  const chars = '0123456789abcdefghijklmnopqrstuvwxyz';
  let captchaValue = '';
  for (let i = 0; i < 5; i++) {
    const char = chars.charAt(Math.floor(Math.random() * chars.length));
    captchaValue += char;
    ctx.font = `${Math.floor(Math.random() * 2) + 20}px Arial`;
    ctx.textBaseline = 'middle';
    ctx.fillStyle = Math.random() > 0.5 ? '#333' : '#000';
    const x = (i + 1) * (width / 6);
    const y = height / 2;
    ctx.fillText(char, x, y);
  }

  captcha.value = captchaValue;
};

onMounted(() => {
  generateCaptcha();
});
</script>

<style scoped>
.captcha-container {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

canvas {
  margin-right: 10px;
}
</style>